new Vue({
    el: '#app',
    data() {
        return {
            // 菜单
            menu: [
                {class_name: 'icon-datu', text: '大图标'},
                {class_name: 'icon-xiaotu', text: '小图标'},
                /*{class_name: 'icon-liebiao', text: '列表'},*/
                {class_name: 'icon-shuaxin', text: '刷新'},
                {class_name: 'icon-zhongqi', text: '重启录音'},
                /*{class_name: 'icon-xitong', text: '系统管理'},*/
                /*{class_name: 'icon-chaxun', text: '查询'},*/
            ],
            // 当前的obj
            currObj: {},
            result: [],
            ws:{},
            // 列表数据
            listData: [],
            audioArr: [],
            audioArrUrl: [],
            listIdx: 1,
            iconType: 1,
            diskSize: 0,
            diskUsed: 0,
            diskAvail: 0,
            diskUsePercent: 0,
            fpath:'',
            lastTime:'',
            recordTotal:0,
            socket_url:'',
            lockReconnect: false,//是否真正建立连接
        }
    },

    methods: {
        showTitle(item){
            let title
            switch (item.state) {
                case 0:
                    title = '断线'
                    break;
                case 1:
                    title = '空闲'
                    break;
                case 2:
		case 3:
                    title = '摘机'
                    if((item.flag & 1)==1)                
                    	{
                         title = '录音'
                         }
                    break; 
                case 4:
                    title = '禁用'
                    break;
                case 5:
                    title = '振铃'
                    break;
                case 6:
                    title = '拨号'
                    break;
            }
            if((item.flag & 1) && item.state !=0 && item.state !=4){

            }
            else if ((item.flag & 2)&&(item.state !=0 && item.state !=4)){
                title = title+'-监听中'
            }
            return title;
        },
        onContextmenu(item) {
            //http://www.fly63.com/article/detial/7118
            let itemlist = []
             console.log(item)
            if(item.imgflag == 12 ){
                itemlist = [
                    { label: "电压查询", icon: "el-icon-printer" ,onClick: () => {
                            this.voltage(item);
                    }},
                    { label: "取消监听", icon: "el-icon-printer" ,onClick: () => {
                        this.cancelMonitor(item);
                    }},
                    ]
            }
            else{
                itemlist = [
                    { label: "电压查询", icon: "el-icon-printer" ,onClick: () => {
                            this.voltage(item);
                    }},
                    { label: "监听", divided: true, icon: "el-icon-refresh" ,onClick: () => {
                        if(item.state == 0){
                            alert('离线状态，不可监听');return;
                        }
                        if(item.state == 4){
                            alert('禁用状态，不可监听');return;
                        }
                        this.monitor(item);
                    }},
                ]
            }
            this.$contextmenu({
                items: itemlist,
                event,
                //x: event.clientX,
                //y: event.clientY,
                customClass: "class-a",
                zIndex: 3,
                minWidth: 230
            });
            return false;
        },
        // 菜单点击
        menuClick(idx) {
            switch (idx) {
                case 0:
                    this.iconType = 1;//大图标
                    break;
                case 1:
                    this.iconType = -1;//小图标
                    break;
                case 2:
                    this.refresh();//刷新
                    break;
                case 3:
                    this.restartMonitor();
                    break;

            }
        },
        //刷新录音
        refresh(){
            $("#contenttext").html('正在刷新.')
            $('#myModal').modal('show');
            this.onOpen()
             $('#myModal').modal('hide');

        },

        //重启录音
        restartMonitor(){

            if(confirm('重启录音会影响正在录音的\n请确认没有通道正在录音时重启！')==true){
                $("#contenttext").html('正在重启录音.')
                $('#myModal').modal('show');
                let recorder = new proto.recorder;
                recorder.setCommand(proto.recorder.cmd.RESTART);
                recorder.setIsRequest(true);
                serial = recorder.serializeBinary();
                length = serial.byteLength;
                bytes = new Uint8Array(length + 4);
                bytes.set(serial, 4);
                header = new DataView(bytes.buffer, 0, 4);
                header.setUint32(0, length, true);
                this.ws.send(bytes)
                return true;

            }else{

                return false;

            }

        },
        //电压查询
        voltage(item){
            let recorder = new proto.recorder;
            recorder.setTimeStamp("12345");
            recorder.setSequenceNo("5678");
            recorder.setAppId("3579");
            recorder.setCommand(proto.recorder.cmd.VOLTAGE);
            recorder.setIsRequest(true);
            console.log(item.id,'电压查询')

            let chn = new proto.recorder.chn;
            chn.setId(item.id);
            recorder.getChannelList().push(chn);

            var serial = recorder.serializeBinary();
            var length = serial.byteLength;
            var bytes = new Uint8Array(length + 4);
            bytes.set(serial, 4);
            // dataview for set length header
            var header = new DataView(bytes.buffer, 0, 4);
            header.setUint32(0, length, true);

            // writeToScreen("SEND: " + bytes);
            this.ws.send(bytes)
        },
        // 监听
        monitor(item) {
            let recorder = new proto.recorder;
            recorder.setTimeStamp("12345");
            recorder.setSequenceNo("5678");
            recorder.setAppId("3579");
            recorder.setCommand(proto.recorder.cmd.MONITOR);
            recorder.setIsRequest(true);
            //console.log(item.id,'监听')

            let chn = new proto.recorder.chn;
            chn.setId(item.id);
            recorder.getChannelList().push(chn);

            var serial = recorder.serializeBinary();
            var length = serial.byteLength;
            var bytes = new Uint8Array(length + 4);
            bytes.set(serial, 4);
            // dataview for set length header
            var header = new DataView(bytes.buffer, 0, 4);
            header.setUint32(0, length, true);

            // writeToScreen("SEND: " + bytes);
            this.ws.send(bytes)

        }
        ,
        // 取消监听
        cancelMonitor(item) {
            let recorder = new proto.recorder;
            recorder.setTimeStamp("12345");
            recorder.setSequenceNo("5678");
            recorder.setAppId("3579");
            recorder.setCommand(proto.recorder.cmd.STOPMONITOR);
            recorder.setIsRequest(true);
            //console.log(id,'取消监听')
            let chn = new proto.recorder.chn;
            chn.setId(item.id);
            recorder.getChannelList().push(chn);

            var serial = recorder.serializeBinary();
            var length = serial.byteLength;
            var bytes = new Uint8Array(length + 4);
            bytes.set(serial, 4);
            var header = new DataView(bytes.buffer, 0, 4);
            header.setUint32(0, length, true);

            this.ws.send(bytes)
            item.flag = 1;
        },
        onClickLeft() {
            Toast('返回');
        },
        onClickRight() {
            Toast('按钮');
        },
        getSocketUrl(url, param) {
            return new Promise((resolve, reject) => {
                axios.get(url, {params: param})
                    .then(response => {
                        resolve(response.data)
                    }, err => {
                        reject(err)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        onOpen(evt) {
            var recorder = new proto.recorder;
            recorder.setTimeStamp("12345");
            recorder.setSequenceNo("5678");
            recorder.setAppId("3579");
            recorder.setCommand(proto.recorder.cmd.QUERY);
            recorder.setIsRequest(true);
            /*for (var i = 0; i < 10; i++) {
                var chn = new proto.recorder.chn;
                chn.setId(i);
                recorder.getChannelList().push(chn);
            }*/


            var serial = recorder.serializeBinary();
            var length = serial.byteLength;
            var bytes = new Uint8Array(length + 4);
            bytes.set(serial, 4);

            var header = new DataView(bytes.buffer, 0, 4);
            header.setUint32(0, length, true);
            // writeToScreen("SEND: " + bytes);
            this.ws.send(bytes)

            //获取磁盘参数
            recorder.setCommand(proto.recorder.cmd.DISK);
            serial = recorder.serializeBinary();
            length = serial.byteLength;
            bytes = new Uint8Array(length + 4);
            bytes.set(serial, 4);
            header = new DataView(bytes.buffer, 0, 4);
            header.setUint32(0, length, true);
            this.ws.send(bytes)
        },
        onMessage(evt) {
            var reader = new FileReader();
            reader.readAsArrayBuffer(evt.data);
            reader.onload = (e) => {

                let buf = new Uint8Array(reader.result);
                var msg;
                msg = buf.slice(4, buf.byteLength);
                var recorder = proto.recorder.deserializeBinary(msg);
                var chns = recorder.getChannelList();


                if (recorder.getCommand() == proto.recorder.cmd.SEND) {
                    const dataLength = recorder.getData().getData().byteLength;
                    // length of wav header is 44
                    if (dataLength < 44) {
                        return;
                    }
                    const view = new DataView(recorder.getData().getData().buffer, recorder.getData().getData().byteOffset);
                    const blob = new Blob([view], {type: 'audio/wav'});
                    let obj_url = window.URL.createObjectURL(blob);
                    this.currUrl = obj_url;
                    if (this.currUrl) this.playaudio(chns)
                    return;
                } else if (recorder.getCommand() == proto.recorder.cmd.MONITOR) {
                    for (let i = 0; i < chns.length; i++) {
                       // console.log(chns[i].getId(),'监听')
                         for (let k = 0; k < this.listData.length; k++) {
                              if(this.listData[k].id == chns[i].getId()){
                                  this.listData[k].imgflag = 12
                               }
			             }
                        /*console.log("通道id="+chns[i].getId())
                        console.log("通道state="+chns[i].getState())
                        console.log("通道flag="+chns[i].getFlag())
                        console.log("通道vol="+chns[i].getVol())*/
                    }
                    return;
                } else if (recorder.getCommand() == proto.recorder.cmd.STOPMONITOR) {
                     for (let i = 0; i < chns.length; i++) {
                         for (let k = 0; k < this.listData.length; k++) {
                              if(this.listData[k].id == chns[i].getId()){
                                  //console.log(chns[i].getId(),chns[i].getState(),chns[i].getFlag(),'取消监听')
                                  let imgFlag = this.getImgFlag(this.listData[k].state,this.listData[k].flag)
                                   this.listData[k].imgflag = imgFlag 
                               }
			             }
                     }
                    return;
                } else if (recorder.getCommand() == proto.recorder.cmd.DISK) {
                    const len = recorder.getPartitionList().length;
                    for (var i = 0; i < len; i++) {

                        let size = recorder.getPartitionList()[i].getSize() / 1024 / 1024 / 1024
                        size = size.toString();
                        let index = size.indexOf('.')
                        this.diskSize = size.slice(0, index + 3)

                        let used = recorder.getPartitionList()[i].getUsed() / 1024 / 1024 / 1024
                        used = used.toString();
                        index = used.indexOf('.')
                        this.diskUsed = used.slice(0, index + 3)

                        let sy = this.diskSize - this.diskUsed
                        sy = sy.toString();
                        index = sy.indexOf('.')
                        this.diskAvail = sy.slice(0, index + 4)

                        let p = recorder.getPartitionList()[i].getUsePercent() * 100
                        p = p.toString();
                        index = p.indexOf('.')
                        this.diskUsePercent =  p.slice(0, index + 3)

                        this.fpath = recorder.getPartitionList()[i].getMountOn()
                        /*console.log(recorder.getPartitionList()[i].getFilesytem(), 'getFilesytem');
                        console.log(recorder.getPartitionList()[i].getSize(), 'getSize');
                        console.log(recorder.getPartitionList()[i].getUsed(), 'getUsed');
                        console.log(recorder.getPartitionList()[i].getAvail(), 'getAvail');
                        console.log(recorder.getPartitionList()[i].getUsePercent(), 'getUsePercent');
                        console.log(recorder.getPartitionList()[i].getMountOn(), 'getMountOn');*/
                    }
                    this.createChart();
                }
                else if (recorder.getCommand() == proto.recorder.cmd.NOTIFY) {
                    for (let i = 0; i < chns.length; i++) {
                        //console.log(chns[i].getId(),chns[i].getState(),chns[i].getFlag())
                        let imgFlag = this.getImgFlag(chns[i].getState(),chns[i].getFlag())
                        this.listData[chns[i].getId()].imgflag = imgFlag
                        this.listData[chns[i].getId()].flag = chns[i].getFlag()
                        this.listData[chns[i].getId()].state = chns[i].getState()
                    }
                    return;
                }
                else if (recorder.getCommand() == proto.recorder.cmd.VOLTAGE) {
                    for (let i = 0; i < chns.length; i++) {
                        // console.log(chns[i].getId(),'监听')
                        for (let k = 0; k < this.listData.length; k++) {
                            if(this.listData[k].id == chns[i].getId()){
                                this.listData[k].vol = chns[i].getVol()
                                this.listData[k].showvol = 1;
                                $("#voltitle").html(chns[i].getId())
                                $("#volval").html(chns[i].getVol())
                                $('#volModal').modal('show');
                            }
                        }
                    }
                    return;
                }
                else if (recorder.getCommand() == proto.recorder.cmd.RESTART) {
                    //console.log(recorder.getIsRequest())
                    if(recorder.getIsRequest() == false){
                        $('#myModal').modal('hide');
                    }
                    return;
                }
                else if (recorder.getCommand() == proto.recorder.cmd.QUERY) {

                    let _arr = [];
                    for (let i = 0; i < chns.length; i++) {
                        //console.log(chns[i].getId(),'通道号')
                        let imgFlag = this.getImgFlag(chns[i].getState(),chns[i].getFlag())
                        let obj = {id: chns[i].getId(), state: chns[i].getState(), flag: chns[i].getFlag(),showvol:0,vol:chns[i].getVol(),imgflag:imgFlag};
                        _arr.push(obj);
                    }
                    this.listData = _arr;
                   // console.log(_arr)
                    return;
                }

            }
        },
        getImgFlag(state,flag){
            let img = state;
            if(((flag & 2)==2)&&(state!=0 && state !=4)){
                img = 12;
            }
            return img
        },

        createChart() {
            // 基于准备好的dom，初始化echarts实例
            //https://www.echartsjs.com/examples/zh/index.html#chart-type-pie
            var myChart = echarts.init(document.getElementById('container'));
            // 绘制图表
            myChart.setOption({
                tooltip: {
                    trigger: 'item',
                    formatter: '{b} : {c} ({d}%)'
                },
                legend: {
                    // orient: 'vertical',
                    // top: 'middle',
                    bottom: 10,
                    left: 'center',
                    data: ['已用空间', '剩余空间']
                },
                series: [
                    {
                        type: 'pie',
                        radius: '65%',
                        center: ['50%', '50%'],
                        selectedMode: 'single',
                        data: [
                            {value: this.diskUsePercent, name: '已用空间'},
                            {value: 100 - this.diskUsePercent, name: '剩余空间'}
                        ],
                        color : [ '#ccc', '#57A1E7'],
                    }
                ]

            });


        },
        playaudio(chns) {
            for (let i = 0; i < chns.length; i++) {
                if(Array.isArray(this.audioArrUrl[chns[i].getId()]) == false){
                    this.audioArrUrl[chns[i].getId()] = []
                }
                if (typeof (this.audioArr[chns[i].getId()]) == "undefined") {
                    this.audioArr.push(chns[i].getId())
                    this.audioArr[chns[i].getId()] = new Audio()
                    this.audioArr[chns[i].getId()].id = "audio_" + chns[i].getId();
                    document.body.appendChild(this.audioArr[chns[i].getId()])  //把它添加到页面中
                }


                this.audioArrUrl[chns[i].getId()].push(this.currUrl);
                //console.log(this.audioArrUrl[chns[i].getId()])
                if(this.audioArrUrl[chns[i].getId()].length>0){
                    this.playaudioArr(this.audioArrUrl[chns[i].getId()],this.audioArr[chns[i].getId()]);
                }

            }
        },
        playaudioArr(arrUrl,audio){
            audio.autoplay = true
            audio.src = arrUrl.pop();  //播放完就读取下一条
        },
        connectWebsocket() {
            // 监听连接成功
            let self = this
            this.ws.onopen = (evt) => {
                //$('#myModal').css('display','none');
                $('#myModal').modal('hide');
                console.log('连接服务端WebSocket成功');
                this.onOpen();

            };
            // 监听服务端消息(接收消息)
            this.ws.onmessage = (msg) => {
                // let message = JSON.parse(msg.data);
                //console.log('收到的消息：', msg);
                this.onMessage(msg)
            };

            // 监听连接失败
            this.ws.onerror = () => {
                /*$('#myModal').modal('hide');
                $("#contenttext").html('连接失败，正在重连...')
                $('#myModal').modal('show');*/
                self.reconnect()

            };
            // 监听连接关闭
            this.ws.onclose = () => {
                $("#contenttext").html('连接录音主线程失败，系统无法录音，请与系统维护人员联系！')
                console.log('连接录音主线程失败，系统无法录音，请与系统维护人员联系！');
                var test2 = setTimeout(function () {
                    //新连接
                    $('#myModal').modal('hide');
                    self.reconnect()
                },2000);
 
            };
        },
        reconnect() {//重新连接
            var that = this;
            if(that.lockReconnect) {
                return;
            };
            that.lockReconnect = true;
            var test2 = setTimeout(function () {
                //新连接
                that.initWebSocket();
                that.lockReconnect = false;
            },5000);
        },
        initWebSocket(){
            let obj = {
                token: '020551'
            }
            $("#contenttext").html('正在连接录音服务器...')
            $('#myModal').modal('show');

            let url =location.protocol+'//'+location.hostname+':'+location.port+'/home/login/indexInfo'
            this.getSocketUrl(url, obj).then((value)=>{
                this.socket_url = value.socketUrl
                this.recordTotal = value.recordInfo.recordTotal
                this.lastTime = value.recordInfo.lastTime
                this.ws = new WebSocket(this.socket_url);
                if ("WebSocket" in window)
                {
                    this.connectWebsocket();
                }
                else{
                    alert("您的浏览器不支持 WebSocket!");
                }
            })
        }
       /* show(idx) {
            this.listIdx = idx - 1;
            this.currObj = this.listData[this.listIdx];
            this.operation = new Array();
            console.log(this.listData[idx - 1],222)
            if (this.listData[idx - 1].flag == 2) {
                this.operation = [{txt: "取消监听", state: 3}, {txt: "禁用", state: 4}]
            } else {
                this.operation = [{txt: "监听", state: 1}, {txt: "禁用", state: 4}]
            }
            return;
        }*/
    },
    mounted() {
        this.$nextTick(() => {
            this.initWebSocket()
        });
    }
});